import * as actions from '../actions/index';

// 页面初始化数据
function getInitialState(pageInfo) {
  const { resourceSubject } = pageInfo;
  const resourcePath = resourceSubject.path || '';
  // 页面初始化数据
  const initialState = {
    commits: [],
    isLoadingList: false,
    filterText: '',
    isLoading: false,
    resourcePath,
  };
  return initialState;
}

const defaultAction = {
  type: 'doNothing',
};

export default function index(state = getInitialState(window.FORCE), action = defaultAction) {
  switch (action.type) {
    case actions.UPDATE_DATA:
      return { ...state, ...action.data };
    case actions.RECEIVE_BUILDS: {
      const { commits } = state;

      const builds = action.data;
      builds.forEach((item) => {
        if (item.length) {
          const thisCommit = commits.find((commit) => commit.id === item[0].sha);
          thisCommit.builds = item;
        }
      });
      return { ...state, commits: [...commits] };
    }
    case actions.UPDATE_PAGE_INFO:
      return getInitialState(action.data);
    default:
      return state;
  }
}
